package com.xc.erp.modules.erp.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xc.erp.common.annotation.Log;
import com.xc.erp.common.constants.ExceptionConstants;
import com.xc.erp.common.utils.SecurityUtils;
import com.xc.erp.common.utils.StringUtils;
import com.xc.erp.modules.erp.domain.AjaxResult;
import com.xc.erp.modules.erp.domain.pojo.JshRole;
import com.xc.erp.modules.erp.domain.pojo.JshTenant;
import com.xc.erp.modules.erp.domain.pojo.JshUser;
import com.xc.erp.modules.erp.domain.pojo.JshUserRole;
import com.xc.erp.modules.erp.service.JshRoleService;
import com.xc.erp.modules.erp.service.JshTenantService;
import com.xc.erp.modules.erp.service.JshUserRoleService;
import com.xc.erp.modules.erp.service.JshUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Api(tags = "用户", value = "用户接口")
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private JshUserService jshUserService;

    @Autowired
    private JshRoleService jshRoleService;

    @Autowired
    private JshUserRoleService jshUserRoleService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation("用户列表")
    @GetMapping("/list/{pageNum}/{pageSize}")
    public AjaxResult list(@PathVariable Integer pageNum, @PathVariable Integer pageSize, String username,String loginName) {
        Page<JshUser> jshUserPage = new Page<>(pageNum, pageSize);
        QueryWrapper<JshUser> queryWrapper=new QueryWrapper<>();
        if (!StringUtils.isEmpty(username)){
            queryWrapper.like("username",username);
        }else if (!StringUtils.isEmpty(loginName)) {
            queryWrapper.like("login_name",loginName);
        }
        IPage<JshUser> byPage = jshUserService.findByPage(jshUserPage, queryWrapper);

        return AjaxResult.success(byPage);
    }

    @ApiOperation("查询下拉角色列表")
    @PostMapping("/selectRole")
    public AjaxResult selectRole(){
        List<JshRole> roles = jshRoleService.list();
        return AjaxResult.success(roles);
    }

    @Log(modul = "用户管理",desc = "新增")
    @ApiOperation("新增用户及机构和用户关系")
    @PostMapping("/addUser")
    public AjaxResult addUser(@RequestBody JshUser jshUser) {
        jshUser.setDeleteFlag("0");
        jshUser.setTenantId(SecurityUtils.getLoginUser().getJshUser().getTenantId());
        jshUser.setPassword(passwordEncoder.encode("123456"));
        int insert = jshUserService.getBaseMapper().insert(jshUser);
        if (insert>0){
            QueryWrapper<JshRole> queryWrapper=new QueryWrapper();
            queryWrapper.eq("name",jshUser.getName());
            JshRole jshRole = jshRoleService.getBaseMapper().selectOne(queryWrapper);
            JshUserRole jshUserRole = new JshUserRole(jshRole.getId(),jshUser.getId());
            jshUserRoleService.save(jshUserRole);
        }
        return AjaxResult.success();
    }

    @Log(modul = "用户管理",desc = "修改")
    @ApiOperation("修改用户及机构和用户关系")
    @PutMapping("/updateUser")
    public AjaxResult update(@RequestBody JshUser jshUser) {
        jshUserService.getBaseMapper().updateById(jshUser);
        return AjaxResult.success();
    }

    @Log(modul = "用户管理",desc = "删除")
    @ApiOperation("删除用户")
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Integer id) {
        if (jshUserService.removeByUserId(id)){
            return AjaxResult.success();
        } else {
            return AjaxResult.error(ExceptionConstants.USER_DELETE_FAILED_MSG);
        }
    }

    @GetMapping("/getCurrentInfo")
    public AjaxResult getCurrentInfo() {
        return AjaxResult.success();
    }


    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Log(modul = "用户管理",desc = "批量删除")
    @ApiOperation("批量删除")
    @DeleteMapping("/deleteBatch")
    public AjaxResult deleteBatch(@RequestBody Long[] ids) {
        if(jshUserService.removeBatchByUserIds(ids)){
            return AjaxResult.success();
        } else {
            return AjaxResult.error(ExceptionConstants.USER_DELETE_FAILED_MSG);
        }
    }


    /**
     * 批量启用/禁用
     *
     * @return
     */
    @Log(modul = "用户管理",desc = "批量启用/禁用")
    @ApiOperation("批量启用/禁用")
    @PostMapping("/batchSetStatus/{status}")
    public AjaxResult batchSetStatus(@RequestBody Long[] ids,@PathVariable Byte status) {
        jshUserService.batchSetStatus(ids, status);
        return AjaxResult.success();
    }

    /**
     * 判断名称是否存在
     *
     * @param loginName
     * @return
     */
    @ApiOperation("检查登录名字是否存在")
    @GetMapping("/checkIsLoginNameExist")
    public AjaxResult checkIsLoginNameExist(Long id,String loginName) {
        boolean status = jshUserService.checkIsLoginNameExist(id,loginName);
        return AjaxResult.success().put("status",status);
    }

    @ApiOperation("检查用户名是否存在")
    @GetMapping("/checkIsUserNameExist")
    public AjaxResult checkIsUserNameExist(Long id,String userName) {
        boolean status = jshUserService.checkIsUserNameExist(id,userName);
        return AjaxResult.success().put("status",status);
    }

    @Log(modul = "用户管理",desc = "重置密码")
    @ApiOperation("重置密码")
    @PostMapping("/resetPwd/{id}")
    public AjaxResult resetPwd(@PathVariable Long id){
        JshUser jshUser=new JshUser();
        jshUser.setId(id);
        jshUser.setPassword(passwordEncoder.encode("123456"));
        jshUserService.updateById(jshUser);
        return AjaxResult.success();
    }
}
